<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRole">添加角色</el-button>
                </el-col>
            </el-row>



            <!-- 角色列表区域 -->
            <el-table :data="roleslist" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom', i1 == 0 ? 'bdtop' : '', 'vcenter']"
                            v-for="(item1, i1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限权限 -->
                            <el-col :span="19">
                                <!-- 通过for循环嵌套渲染二级权限 -->
                                <el-row :class="['bdbottom', i2 === 0 ? '' : 'bdtop', 'vcenter']"
                                    v-for="(item2, i2) in item1.children" :key="item2.id">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">
                                            {{ item2.authName }}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <el-tag type="warning" v-for="(item3, i3) in item2.children" :key="item3.id"
                                            closable @close="removeRightById(scope.row, item3.id)">
                                            {{ item3.authName }}
                                        </el-tag>
                                    </el-col>

                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="setListDate(scope.row.id)">编辑
                        </el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除
                        </el-button>
                        <el-button size="mini" type="warning" icon="el-icon-setting"
                            @click="showSetRightDialog(scope.row)">分别权限
                        </el-button>
                    </template>
                </el-table-column>

            </el-table>

        </el-card>

        <!-- 分配权限的对话框 -->
        <el-dialog title="分别权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">

            <!-- 树形控件 -->
            <el-tree ref="treeRef" :data="rightsList" :props="treeProps" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="defKeys"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加角色的对话框 -->
        <el-dialog title="添加角色" :visible.sync="CharacterBox" width="50%">
            <!-- 弹框的内容主体区域 -->
            <el-form ref="rolesFormRef" :model="addRoles" :rules="addRolesRules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoles.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoles.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="CharacterBox = false">取 消</el-button>
                <el-button type="primary" @click="rolesChecking">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改角色的数据 -->
        <el-dialog title="修改角色" :visible.sync="setRolesDate" width="50%" @close="closeboxRoles">
            <el-form ref="setRolesRef" :model="setRolesModel" :rules="setRolesRules" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="setRolesModel.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="setRolesModel.roleDesc"></el-input>
                </el-form-item>
            </el-form>


            <span slot="footer" class="dialog-footer">
                <el-button @click="setRolesDate = false">取 消</el-button>
                <el-button type="primary" @click="setDateRoles">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import api from '@/api/index'
export default {
    name: 'Roles',
    data() {
        return {
            //所有角色的列表数据
            roleslist: [],
            //控制分配权限对话框
            setRightDialogVisible: false,
            //所有权限的数据
            rightsList: [],
            //树形控件
            treeProps: {
                label: 'authName',
                children: 'children'
            },
            //默认的选中的节点
            defKeys: [],
            //当前即将分配权限的角色iD
            roloId: '',
            //添加角色的弹出框
            CharacterBox: false,
            //添加角色的数据
            addRoles: {
                roleName: '',
                roleDesc: ''
            },
            //修改角色的数据
            setRolesDate: false,
            setRolesModel: {},


            //验证规则
            addRolesRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 6, message: '角色名称在2~6字符之间', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色的描述', trigger: 'blur' },
                    { min: 2, max: 10, message: '角色描述在2~10个字符之间', trigger: 'blur' }
                ]
            },
            setRolesRules: {
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 6, message: '角色名称在2~6字符之间', trigger: 'blur' }
                ],
                roleDesc: [
                    { required: true, message: '请输入角色的描述', trigger: 'blur' },
                    { min: 2, max: 10, message: '角色描述在2~10个字符之间', trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        //获取所有角色的列表
        async getRolesList() {
            const result = await api.rolesList()
            if (result.meta.status !== 200) return this.$message.error('获取角色列表失败!')
            this.roleslist = result.data
            console.log(this.roleslist);
        },
        //根据id删除对应的权限
        async removeRightById(role, rightId) {
            // 弹框提示用户是否删除
            const confirmResult = await this.$confirm('此操作将删除该角色的权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const result = await api.rolesPower({
                    roleId: role.id,
                    rightId: rightId
                })
                if (result.meta.status !== 200) return this.$message.error('删除权限失败!')
                role.children = result.data
                this.$message.success('删除成功!')
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //展示分配权限的对话框
        async showSetRightDialog(role) {
            this.roloId = role.id
            //获取权限数据
            const result = await api.rolesListTree()
            if (result.meta.status !== 200) return this.$message.error('获取权限列表失败!')
            this.rightsList = result.data

            //递归获取三级节点的id
            this.getLeafKeys(role, this.defKeys)
            this.setRightDialogVisible = true
        },
        //通过递归的形式,获取角色下所有三级权限的ID，并保存到defKeys
        getLeafKeys(node, arr) {
            if (!node.children) {
                return arr.push(node.id)
            }

            node.children.forEach(item => {
                this.getLeafKeys(item, arr)
            })
        },
        //监听分配权限对话框的关闭事件
        setRightDialogClosed() {
            this.defKeys = []
        },
        //分配权限的函数
        async allotRights() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')
            const result = await api.roleAuth({
                roleId: this.roloId,
                rids: idStr
            })

            if (result.meta.status !== 200) return this.$message.error('分配权限失败!')
            this.$message.success('分配权限成功!')
            this.getRolesList()
            this.setRightDialogVisible = false
        },
        //添加角色的弹出框
        addRole() {
            this.CharacterBox = true
        },
        //添加角色数据,并验证规则
        rolesChecking() {
            this.$refs.rolesFormRef.validate(async valid => {
                if (!valid) return
                const result = await api.addrolesDate({
                    roleName: this.addRoles.roleName,
                    roleDesc: this.addRoles.roleDesc
                })
                if (result.meta.status !== 201) return this.$message.error('添加角色数据失败!')
                this.$message.success('添加角色数据成功!')

                this.CharacterBox = false
                this.getRolesList()
            })
        },
        //通过id获取角色数据,并渲染到页面上
        async setListDate(setId) {
            const result = await api.getRolesId({
                id: setId
            })
            if (result.meta.status !== 200) return this.$message.error('"获取角色数据失败!')
            this.setRolesModel = result.data
            this.setRolesDate = true
        },
        //修改角色数据
        setDateRoles() {
            this.$refs.setRolesRef.validate(async valid => {
                if (!valid) return
                const result = await api.setRolesDate({
                    id: this.setRolesModel.roleId,
                    roleName: this.setRolesModel.roleName,
                    roleDesc: this.setRolesModel.roleDesc
                })
                if (result.meta.status !== 200) return this.$message.error('修改角色数据失败!')

                this.$message.success('修改角色数据成功!')
                this.getRolesList()
                this.setRolesDate = false
            })
        },
        //监听修改角色弹框的关闭事件
        closeboxRoles() {
            this.$refs.setRolesRef.resetFields()
        },
        //删除角色的数据
         deleteRoles(id) {
            this.$confirm('此操作将永久角色数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const result = await api.deleteDateRoles({
                    id: id
                })
                if (result.meta.status !== 200) return this.$message.error('删除角色数据失败!')
                this.$message.success('删除角色数据成功!')
                this.getRolesList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 8px;
}

.bdtop {
    border-top: 1px soli #eee;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>